var express = require('express');
var router = express.Router();
var config = require('../config/db')
var MongoClient = require('mongodb').MongoClient
var bcrypt = require('bcryptjs')
var passport = require('passport')
var mongdb = require('mongodb')

/* 获取（查询）地址信息 */
router.get('/getAddressInfo', passport.authenticate('jwt', { session: false }), async function (req, res, next) {
    let client = await MongoClient.connect(config.url)
    let db = client.db()
    let address = await db.collection('address').find({ user_id: req.user._id }).sort({ 'address_addTime': -1 }).toArray()
    if (address.length >= 0) {
        res.json({ code: 200, message: 'ok ', data: address });
    }
    else {
        res.json({ code: 200, message: 'error' });
    }
});


/* 添加地址 */
router.post('/addAddress', function (req, res, next) {
    //1.接受添加地址需要使用的参数req.body（consignee，addressDdetails，addressStatus）
    var insertAddress = req.body.address
    console.log('req.body', req.body)
    //2.连接数据库MongoDB
    MongoClient.connect(config.url, function (err, client) {
        if (err) {
            console.log('数据库连接失败！', err)
            res.json({ code: 200, message: 'error', data: err })
        } else {
            //3.执行添加操作 db.insertOne
            var db = client.db()
            var addAddress = {
                user_id: insertAddress.userId,
                address_details: insertAddress.addressDdetails,
                address_phone: insertAddress.addressPhone,
                address_receive: insertAddress.addressReceive,
                address_addTime: new Date().toLocaleString()
            }
            db.collection('address').insertOne(addAddress, function (err, result) {
                if (err) {
                    console.log('添加数据失败！', err)
                } else {
                    //4.返回结果{code:0;message:'ok',data:{}}
                    res.json({ code: 200, message: 'ok', data: result })
                    client.close()
                }
            })
        }
    })
});


/*删除地址*/
router.delete('/delAddress', passport.authenticate('jwt', { session: false }), async function (req, res, next) {
    // 获取需要删除的id
    let id = req.query.id
    console.log('id =', id)
    //获取数据库连接对象
    let client = await MongoClient.connect(config.url)
    let db = client.db()
    //执行删除的操作
    let results = await db.collection('address').deleteOne({ _id: new mongdb.ObjectId(id) })
    console.log('results:', results)
    //判断是否删除成功
    if (results.acknowledged) {
        res.json({
            code: 200, message: 'ok'
        });
    } else {
        res.json({
            code: 200, message: 'error'
        });
    }
});

/* 修改地址信息*/
router.get('/updAddress', function (req, res, next) {
    res.send('修改地址信息');
});

module.exports = router;